package designpattern.prodecterconsumer;

import java.util.LinkedList;
import java.util.Queue;
//生产者消费者模式
public class MyContainer<T> {
    final private Queue<T >queue=new LinkedList<>();
    private final int Max=3;
    private int count=0;
    public synchronized void add(T t){
        while (count==Max){
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        queue.add(t);
        System.out.println(Thread.currentThread().getName()+"生产了");

        ++count;
        this.notifyAll();
    }
    public synchronized T get(){
        while (count==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        --count;
        T s=queue.poll();
        System.out.println(Thread.currentThread().getName()+"消费了"+s);

        this.notifyAll();
        return s;
    }

    public static void main(String[] args) {
        MyContainer<String>myContainer=new MyContainer<>();
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                    myContainer.add(Thread.currentThread().getName());

            }).start();
        }
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                String s=myContainer.get();
            }).start();
        }
    }
}
